package com.da.lon.wang.xlg.imgupload;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class ChooseListActivity extends Activity implements
        OnItemClickListener, OnClickListener {

    private ListView listView;
    private List<String> list;
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
    private HashSet<String> mDirPaths = new HashSet<String>();
    private String flg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xlg_image_list);
        MyApplication.getInstance().addActivity(this);
        getImages();
        initView();
        Intent intent = getIntent();
        flg = intent.getStringExtra("flg");
    }

    private void initView() {
        try {
            ((ImageButton) findViewById(R.id.image)).setVisibility(View.GONE);
            ((RelativeLayout) findViewById(R.id.top_rl))
                    .setBackgroundColor(Color.parseColor("#f0f0f0"));
            TextView title = (TextView) findViewById(R.id.title);
            title.setText("选择照片");
            title.setTextColor(Color.parseColor("#000000"));
            ImageButton back = (ImageButton) findViewById(R.id.back);
            back.setImageResource(R.drawable.xlg_back_grey);
            back.setOnClickListener(this);
            listView = (ListView) findViewById(R.id.list);
            listView.setOnItemClickListener(this);
            listView.setAdapter(new ImageListAdapter(this, "", mImageFloders));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getImages() {
        try {
            if ("mounted".equals(Environment.getExternalStorageState())) {
                list = new ArrayList<String>();
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = getContentResolver();
                if (mContentResolver != null) {
                    Cursor mCursor = mContentResolver.query(mImageUri, null,
                            "mime_type =? or mime_type =?", new String[]{
                                    "image/jpeg", "image/png"},
                            "date_modified");

                    while (null != mCursor && mCursor.moveToNext()) {

                        String path = mCursor.getString(mCursor
                                .getColumnIndex(MediaStore.Images.Media.DATA));

                        File parentFile = new File(path).getParentFile();
                        if (parentFile == null)
                            continue;
                        String dirPath = parentFile.getAbsolutePath();
                        ImageFloder imageFloder = null;
                        if (mDirPaths.contains(dirPath)) {
                            continue;
                        } else {
                            mDirPaths.add(dirPath);
                            imageFloder = new ImageFloder();
                            imageFloder.dir = dirPath;
                            imageFloder.firstImagePath = path;
                        }

                        String[] imgs = parentFile.list(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg")
                                        || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg"))
                                    return true;
                                return false;
                            }
                        });
                        if (imgs != null) {
                            imageFloder.count = imgs.length;
                            mImageFloders.add(imageFloder);
                        }
                        list.add(path);
                    }
                    mCursor.close();
                    mDirPaths = null;
                }
            } else {
                Toast.makeText(getApplicationContext(), "找不到存储卡",
                        Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        try {
            if (mImageFloders != null && mImageFloders.size() > position
                    && mImageFloders.get(position) != null
                    && mImageFloders.get(position).dir != null) {
                Intent intent = new Intent(ChooseListActivity.this,
                        PicDetailActivity.class);
                intent.putExtra("dir", mImageFloders.get(position).dir);
                intent.putExtra("flg", flg);
                if (MyApplication.isMyoption()) {
                    startActivityForResult(intent, 200);
                } else {
                    startActivity(intent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            default:
                break;
        }

    }
}
